#!/usr/bin/env node
/**
 * Service connectivity test script for CB Document Helper MCP Server
 * This script tests the connection to Qdrant and Ollama services
 */

async function testQdrant() {
  try {
    console.log('Testing Qdrant connection...');
    
    const { QdrantClient } = require('@qdrant/js-client-rest');
    const client = new QdrantClient({ host: 'localhost', port: 6333 });
    
    // Test basic connection with timeout
    const collections = await Promise.race([
      client.getCollections(),
      new Promise((_, reject) => setTimeout(() => reject(new Error('Connection timeout')), 5000))
    ]);
    
    console.log('✅ Qdrant connection successful');
    console.log(`   Collections: ${collections.collections.length}`);
    
    return true;
  } catch (error) {
    console.log('❌ Qdrant connection failed:', error.message);
    console.log('   Make sure Qdrant is running on localhost:6333');
    console.log('   Start with: docker run -p 6333:6333 qdrant/qdrant');
    return false;
  }
}

async function testOllama() {
  try {
    console.log('Testing Ollama connection...');
    
    const { Ollama } = require('ollama');
    const ollama = new Ollama({ host: 'http://localhost:11434' });
    
    // Test basic connection with timeout
    const models = await Promise.race([
      ollama.list(),
      new Promise((_, reject) => setTimeout(() => reject(new Error('Connection timeout')), 5000))
    ]);
    
    console.log('✅ Ollama connection successful');
    console.log(`   Available models: ${models.models.length}`);
    
    // Check for required models
    const modelNames = models.models.map(m => m.name);
    console.log(`   Models: ${modelNames.slice(0, 3).join(', ')}${modelNames.length > 3 ? '...' : ''}`);
    
    const hasEmbedding = modelNames.some(name => name.includes('bge-m3'));
    const hasSummary = modelNames.some(name => name.includes('qwen2.5'));
    
    if (hasEmbedding) {
      console.log('✅ BGE-M3 embedding model found');
    } else {
      console.log('⚠️  BGE-M3 embedding model not found');
      console.log('   Run: ollama pull bge-m3');
    }
    
    if (hasSummary) {
      console.log('✅ Qwen2.5 summary model found');
    } else {
      console.log('⚠️  Qwen2.5 summary model not found');
      console.log('   Run: ollama pull qwen2.5');
    }
    
    return true;
  } catch (error) {
    console.log('❌ Ollama connection failed:', error.message);
    console.log('   Make sure Ollama is running on localhost:11434');
    console.log('   Install from: https://ollama.ai');
    return false;
  }
}

async function main() {
  console.log('CB Document Helper MCP Server - Service Connectivity Test');
  console.log('=========================================================\n');
  
  try {
    const qdrantOk = await testQdrant();
    console.log('');
    const ollamaOk = await testOllama();
    
    console.log('\n=========================================================');
    if (qdrantOk && ollamaOk) {
      console.log('🎉 All services are ready! You can start the MCP server.');
      console.log('   Run: npm run start');
    } else {
      console.log('⚠️  Some services need attention before starting the MCP server.');
      console.log('   Fix the issues above and run this test again.');
    }
  } catch (error) {
    console.error('❌ Test script failed:', error.message);
    console.error('   Please check your Node.js version and dependencies.');
  }
}

if (require.main === module) {
  main().catch(console.error);
}
